﻿#region License
/*
Copyright (c) 2005-2010, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Using
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using AO.Core;
#endregion

namespace ZoneEngine
{
    #region StatTypes Class
    /// <summary>
    /// 
    /// </summary>
    public class StatTypes2
    {
        #region Constructors
        /// <summary>
        /// 
        /// </summary>
        public StatTypes2()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statName"></param>
        public StatTypes2(int statId, string statName)
        {
            this.statId = statId;
            this.statName = statName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statName"></param>
        /// <param name="defaultValue"></param>
        public StatTypes2(int statId, string statName, int defaultValue)
            : this(statId, statName)
        {
            this.defaultValue = defaultValue;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statName"></param>
        /// <param name="statFullName"></param>
        public StatTypes2(int statId, string statName, string statFullName)
            : this(statId, statName)
        {
            this.statFullName = statFullName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statName"></param>
        /// <param name="defaultValue"></param>
        /// <param name="statFullName"></param>
        public StatTypes2(int statId, string statName, int defaultValue, string statFullName)
            : this(statId, statName, statFullName)
        {
            this.defaultValue = defaultValue;
        }
        #endregion

        [XmlAttribute("id")]
        public int statId;

        [XmlAttribute("Name")]
        public string statName;

        [XmlElement("FullName")]
        public string statFullName = string.Empty;

        [XmlElement("Default")]
        public int defaultValue = 1234567890;
    }
    #endregion

    #region StatsList Class
    /// <summary>
    /// 
    /// </summary>
    [XmlRoot("Stats")]
    public class StatsList2
    {
        [XmlIgnore]
        public static readonly StatsList2 Instance;

        #region Constructors
        private StatsList2()
        {
        }

        static StatsList2()
        {
            Instance = LoadXML(System.IO.Path.Combine("XML Data", "Stats.xml"));
        }
        #endregion

        #region XML
        // Generally this shouldn't be used outside of the static constructor
        static public StatsList2 LoadXML(string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(StatsList));
            TextReader reader = new StreamReader(fileName);
            StatsList2 data = (StatsList2)serializer.Deserialize(reader);
            reader.Close();
            return data;
        }

        // This really should only be used for development. Included for completeness.
        static public void DumpXML(string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(StatsList));
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add(String.Empty, String.Empty);
            TextWriter writer = new StreamWriter(fileName);
            serializer.Serialize(writer, Instance, xsn);
            writer.Close();
        }
        #endregion

        [XmlElement("Stat")]
        public List<StatTypes2> stats;

        /// <summary>
        ///     
        /// </summary>
        /// <param name="statName"></param>
        /// <returns></returns>
        public static int GetStatId(string statName)
        {
            if (statName == string.Empty)
                return 0;

            try
            {
                // Are we passed a StatId? If so, return it as an int

                int statId = int.Parse(statName);

                if (statId > 0)
                    return statId;
            }
            catch (Exception)
            {
            }

            foreach (StatTypes2 stat in Instance.stats)
            {
                if (stat.statName.ToLower() == statName.ToLower())
                    return stat.statId;
            }

            Console.WriteLine("Unknown statName: " + statName);

            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <returns></returns>
        public static string GetStatName(int statId)
        {
            foreach (StatTypes2 stat in Instance.stats)
            {
                if (stat.statId == statId)
                    return stat.statName;
            }

            Console.Write("Unknown statId: " + statId);

            return "UnknownStat#" + statId;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <returns></returns>
        public static int GetDefaultValue(int statId)
        {
            foreach (StatTypes2 stat in Instance.stats)
            {
                if (stat.statId == statId)
                    return stat.defaultValue;
            }

            Console.WriteLine("Using generic DefaultValue for statId " + statId);

            // Generic default value
            return 1234567890;
        }
    }
    #endregion

    #region MobsStat Class
    public class MobStat
    {
        public int statId;
        public int statValue;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statValue"></param>
        public MobStat(int statId, int statValue)
        {
            this.statId = statId;
            this.statValue = statValue;
        }
    }
    #endregion

    #region MobsStats Class
    public class MobsStats
    {
        #region Mysql
        private MySqlWrapper mySql = new MySqlWrapper();
        #endregion

        List<MobStat> statsTable = new List<MobStat>();

        public bool ReadStats(Mob mob)
        {
            int numberOfStats = 0;
            mySql.MySqlRead("SELECT `Stat`, `Value` FROM `mob_stats` WHERE `ID` = " + mob.mobId + ";");

            while (mySql.myreader.Read())
            {
                int statId = mySql.myreader.GetInt32(0);

                if (statId == 10) // ProfessionLevel is based off Level
                    continue;
                // Type and Instance - same deal as above, shouldn't happen, but just in case...
                if (statId == 1001)
                    continue;
                if (statId == 1002)
                    continue;

                statsTable.Add(new MobStat(statId, mySql.myreader.GetInt32(0)));
                numberOfStats++;
            }
            mySql.myreader.Close();
            mySql.mcc.Close();
            
            statsTable.Add(new MobStat(10, Math.Min(200, GetStat(54))));
            statsTable.Add(new MobStat(1001, 50000)); // Type
            statsTable.Add(new MobStat(1002, mob.mobId)); //Instance

            return numberOfStats > 0;
        }
        public bool WriteStats(Mob mob)
        {
            int numberOfStats = 0;
            string sql = string.Empty;
            string sqlUpdatedStats = string.Empty;
            string startSqlValue = "(" + mob.mobId + ", ";

            sql += "REPLACE INTO `mob_stats` (`ID`, `Stat`, `Value`) VALUES ";

            foreach (MobStat stat in statsTable)
            {
                if ((stat.statId == 1234567890) || (stat.statValue == 1234567890)) // No point saving default value stats
                    continue;

                //if ((stat.statId == 389) || (stat.statId == 660) || (stat.statId == 607)) // Expansion, AccountFlags and PlayerID are obtained from the login table
                 //   continue;

                if (stat.statId == 10) // ProfessionLevel is based off Level
                    continue;

                //if (stat.statId == 215) // GmLevel is based off GM flag in Login table
                 //   continue;

                if ((stat.statId == 1001) || (stat.statId == 1002)) // Type and Instance
                    continue;

                if (stat.statValue == StatsList.GetDefaultValue(stat.statId)) // No point saving default values
                    continue;

                if (numberOfStats > 0)
                    sql += ",";

                sql += startSqlValue + stat.statId + ", " + stat.statValue + ")";

                sqlUpdatedStats += " AND `Stat` != " + stat.statId;

                numberOfStats++;
            }

            sql += ";";

            mySql.MySqlDelete("DELETE FROM `mob_stats` WHERE `ID` = " + mob.mobId + sqlUpdatedStats + ";");
            mySql.MySqlInsert(sql);

            return numberOfStats > 0;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="charId"></param>
        /// <param name="statName"></param>
        /// <param name="statValue"></param>
        /// <returns></returns>
        //public static bool SetOtherStat(Client client, int mobId, string statName, int statValue)
        //{
         //   return SetOtherStat(client, mobId, StatsList.GetStatId(statName), statValue);
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <returns></returns>
        public int GetStat(int statId)
        {
            foreach (MobStat stat in statsTable)
            {
                if (stat.statId == statId)
                    return stat.statValue;
            }

            // Character does not have the stat set, lets find the default stat value for this then
            return StatsList.GetDefaultValue(statId);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statName"></param>
        /// <returns></returns>
        public int GetStat(string statName)
        {
            return GetStat(StatsList.GetStatId(statName));
        }

        /// <summary>
        /// Removes a stat from the stat table leaving the character with the default value.
        /// Should really only be used for org rank. Please don't use this unless you really
        /// know what you're doing or it can break things. Poke NV if unsure. There shouldnt
        /// be many instances where this is needed really...
        /// </summary>
        /// <param name="statId"></param>
        /// <returns></returns>
        public bool RemoveStat(int statId)
        {
            foreach (MobStat stat in statsTable)
            {
                if (stat.statId == statId)
                {
                    statsTable.Remove(stat);
                    return true;
                }
            }

            // Mob does not have the stat set.
            return false;
        }

        /// <summary>
        /// Removes a stat from the stat table leaving the character with the default value.
        /// Should really only be used for org rank. Please don't use this unless you really
        /// know what you're doing or it can break things. Poke NV if unsure. There shouldnt
        /// be many instances where this is needed really...
        /// </summary>
        /// <param name="statName"></param>
        /// <returns></returns>
        public bool RemoveStat(string statName)
        {
            return RemoveStat(StatsList.GetStatId(statName));
        }

        // Returns true if stat already existed, false if stat had to be added to the list
        /// <summary>
        /// 
        /// </summary>
        /// <param name="statId"></param>
        /// <param name="statValue"></param>
        /// <returns></returns>
        public bool SetStat(int statId, int statValue)
        {
            foreach (MobStat stat in statsTable)
            {
                if (stat.statId == statId)
                {
                    stat.statValue = statValue;

                    return true;
                }
            }

            statsTable.Add(new MobStat(statId, statValue));

            return false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="statName"></param>
        /// <param name="statValue"></param>
        /// <returns></returns>
        public bool SetStat(string statName, int statValue)
        {
            return SetStat(StatsList.GetStatId(statName), statValue);
        }
    }
    #endregion
}